package token

import (
	"context"
	"strconv"

	"mall/common/utils/pointy"
	"mall/service/backend/api/internal/logic/system/util"
	"mall/service/backend/api/internal/logic/utils"
	"mall/service/backend/api/internal/logic/utils/parse"
	"mall/service/backend/api/internal/svc"
	"mall/service/backend/api/internal/types"
	"mall/service/backend/common/i18n"
	"mall/service/backend/rpc/backendclient"

	"github.com/zeromicro/go-zero/core/logx"
)

type GetTokenListLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewGetTokenListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetTokenListLogic {
	return &GetTokenListLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *GetTokenListLogic) GetTokenList(req *types.SystemTokenListReq) (resp *types.SystemTokenListResp, err error) {
	page, pageSize := parse.ParsePageInfo(
		req.Current,
		req.PageSize,
		l.svcCtx.Config.Query.DefaultAmount,
		l.svcCtx.Config.Query.MaxAmount,
	)

	orderBys := util.ParseSorter(req.Sorter)
	filterBys := util.ParseFilter(req.Filter)

	var ids *string
	if req.Id != nil && *req.Id > 0 {
		ids = pointy.GetPointer(strconv.FormatInt(int64(*req.Id), 10))
	}

	data, err := l.svcCtx.BackendRpc.GetTokenList(l.ctx, &backendclient.TokenListReq{
		Page:      page,
		PageSize:  pageSize,
		Ids:       ids,
		Uuid:      req.Uuid,
		Username:  req.Username,
		Nickname:  req.Nickname,
		Email:     req.Email,
		Mobile:    req.Mobile,
		Source:    req.Source,
		Status:    req.Status,
		StartTime: req.StartTime,
		EndTime:   req.EndTime,
		OrderBy:   orderBys,
		FilterBy:  filterBys,
	})
	if err != nil {
		return
	}

	resp = &types.SystemTokenListResp{
		BaseDataInfo: types.BaseDataInfo{
			Success: true,
			Msg:     l.svcCtx.Trans.Trans(l.ctx, i18n.Success),
		},
		Data: types.SystemTokenListInfo{
			BaseListInfo: types.BaseListInfo{
				Current:  page,
				PageSize: pageSize,
				Total:    data.GetTotal(),
			},
		},
	}
	for _, v := range data.List {
		option := utils.GetOptionByStatus(v.Status)
		resp.Data.List = append(resp.Data.List, &types.SystemTokenInfo{
			BaseIDInfo: types.BaseIDInfo{
				Id:        v.Id,
				CreatedAt: v.CreatedAt,
				UpdatedAt: v.UpdatedAt,
				CanAccept: option.CanAccept,
				CanReject: option.CanReject,
				CanRemove: option.CanRemove,
			},
			Uuid:      v.Uuid,
			Token:     v.Token,
			Source:    v.Source,
			Status:    v.Status,
			ExpiredAt: v.ExpiredAt,
		})
	}

	return resp, nil
}
